<?php
namespace App\Services;

use App\AccessToken;
use App\Lib\Util\CurlRequest;

class WeixinConfigService
{
    public function getWeixinPlatformConfig($platformId)
    {
        $configs = config('weixin.weixin_configs');

        foreach ($configs as $config) {
            if ($config['key'] == $platformId) {
                return [
                    'appId' => $config['AppId'],
                    'appSecret' => $config['AppSecret']
                ];
            }
        }

        return null;
    }

    public function getAppOpenId($platformId, $authCode)
    {
        $config = $this->getWeixinPlatformConfig($platformId);

        if (isset($config)) {
            $curlRequest = new CurlRequest();

            $weixinAuthUrl = 'https://api.weixin.qq.com/sns/jscode2session?appid='.$config['appId']
                .'&secret='.$config['appSecret'].'&js_code='.$authCode.'&grant_type=authorization_code';

            $curlResult = $curlRequest->httpGet($weixinAuthUrl);

            return json_decode($curlResult, true);
        }

        return null;
    }
}
